function rvalue = vtc_WriteAnalyzeSeries(hfile, pattern, offset, range)
% VTC::WriteAnalyzeSeries  - writes analyze vols for the (entire) TC
%
% FORMAT:       vtc.WriteAnalyzeSeries(pattern, offset, range)
%
% Input fields:
%
%       pattern     output filename pattern
%       offset      volume offset (for filename)
%       range       range of volumes

% Version:  v0.7b
% Build:    7083014
% Date:     Aug-30 2006, 2:16 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1 || ...
    numel(hfile) ~= 1 || ...
   ~isBVQXfile(hfile, 'vtc')
    error( ...
        'BVQXfile:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end

% get number of volumes
bc = bvqxfile_getcont(hfile.L);
numvol = bc.NrOfVolumes;

% check further arguments
if nargin < 4 || ...
   ~isa(range, 'double') || ...
    isempty(range) || ...
    any(isinf(range(:)') | isnan(range(:)')) || ...
    any(fix(range(:)') ~= range(:)' | range(:)' < 1 | range(:)' > numvol)
    range = 1:numvol;
end
range = range(:)';
if length(range) == 2
    range = range(1):range(2);
end
if nargin < 3 || ...
   ~isa(offset, 'double') || ...
    numel(offset) ~= 1 || ...
    isinf(offset) || ...
    isnan(offset) || ...
    fix(offset) ~= offset || ...
    offset < 1 || ...
    offset > 9999
    offset = 1;
end
if nargin < 2 || ...
   ~ischar(pattern) || ...
   ~any(pattern(:)' == '%') || ...
    (isempty(strfind(lower(pattern(:)'), '.img')) && ...
     isempty(strfind(lower(pattern(:)'), '.hdr')))
    pattern = sprintf('vtcvol_%%0%dd.img', length(num2str(numvol + offset - 1)));
end
pattern = pattern(:)';

% loop over images
for vc = range
    tname = sprintf(pattern, vc + offset - 1);
    succ = vtc_WriteAnalyzeVol(hfile, vc, tname);
    if ~succ
        error( ...
            'BVQXfile:InternalError', ...
            'Error writing volume %d to file %s.', ...
            vc, tname ...
        );
    end
end
rvalue = succ;
